import requests


def request_get(url, headers=None, params=None):
    headers = headers or {}
    resp = requests.get(url, headers=headers, params=params)
    if resp.status_code != 200:
        print(f"Error: Unable to access {url}. Status code: {resp.status_code}")
        return None
    return resp.json()


def request_gitee_api(endpoint, params=None):
    base_url = "https://gitee.com/api/v5"
    url = f"{base_url}/{endpoint}"
    return request_get(url, params=params)


def get_pr_info(owner, repo, pr_number):
    endpoint = f"repos/{owner}/{repo}/pulls/{pr_number}"
    pr_data = request_gitee_api(endpoint)
    if pr_data is None:
        raise RuntimeError(f"Error: Unable to fetch PR #{pr_number} for {owner}/{repo}.")
    return pr_data


def get_issue_info(owner, repo, issue_number):
    endpoint = f"repos/{owner}/{repo}/issues/{issue_number}"
    issue_data = request_gitee_api(endpoint)
    if issue_data is None:
        raise RuntimeError(f"Error: Unable to fetch issue #{issue_number} for {owner}/{repo}.")
    return issue_data


def check_ci_successful(owner, repo, pr_number):
    pr_info = get_pr_info(owner, repo, pr_number)
    for label in pr_info.get("labels", []):
        if label["name"] == "ci_successful":
            return True
    return False


def pr_related_to_issue(owner, repo, pr_number):
    pr_info = get_pr_info(owner, repo, pr_number)
    issue_url = pr_info.get("issue_url", "")
    if issue_url:
        issues = request_get(issue_url)
        return issues[0].get("number") 
    return None


def get_issue_content(owner, repo, issue_number):
    issue_info = get_issue_info(owner, repo, issue_number)
    return issue_info.get("body", "")


def check_issue():
    # 1. pr should related to issue
    issue_number = pr_related_to_issue()
    if not issue_number:
        print("PR is not related to any issue.")
        return False
    # 2. issue content should be clear enough
    issue_content = get_issue_content()
    if not issue_content:
        print("Issue content is not clear enough.")
        return False
    print("Issue content: ")
    print("---\n", issue_content, "\n---")
    return True


def check_commit_msg():
    # 1. if patch comes from upstream, inclusion should be mainline or stable
    # 2. commit message should be clear enough
    for commit in get_commits():
        print(get_commit_msg(commit))


def has_unexpected_format_warning():
    pass


def has_unexpected_build_warning():
    pass


def check_format_warning():
    # no unexpected format warning
    if has_unexpected_format_warning():
        print("Unexpected format warning found.")
        return False
    return True


def check_build_warning():
    # 1. no unexpected build warning
    if has_unexpected_build_warning():
        print("Unexpected build warning found.")
        return False
    return True
